using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.WriteApi.Application.Command.Permissions;
using MediatR;

namespace BaseData.WriteApi.Application.CommandHandler.Permissions
{
    /// <summary>
    /// 处理更新权限命令的命令处理器
    /// </summary>
    public class UpdatePermissionCommandHandler : IRequestHandler<UpdatePermissionCommand, Apiresult<int>>
    {
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<UpdatePermissionCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数，注入所需的服务
        /// </summary>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public UpdatePermissionCommandHandler(
            IBasepository<Permission> _permisspository,
            IMapper _mapper,
            ILogger<UpdatePermissionCommandHandler> _logger)
        {
            permisspository = _permisspository;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 处理更新权限命令
        /// </summary>
        /// <param name="request">更新权限的请求数据</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>返回操作结果</returns>
        public async Task<Apiresult<int>> Handle(UpdatePermissionCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找要更新的权限
                var permission = await permisspository.GetModel(p => p.PermissionId == request.PermissionId);
                if (permission == null)
                {
                    return new Apiresult<int>
                    {
                        Code = ResultCode.查询失败,
                        Message = "权限不存在"
                    };
                }

                // 更新权限信息
                permission.PermissionName = request.PermissionName;
                var updateResult = await permisspository.EditAsync(permission);
                if (updateResult <= 0)
                {
                    return new Apiresult<int>
                    {
                        Code = ResultCode.修改失败,
                        Message = "权限信息更新失败"
                    };
                }

                return new Apiresult<int>
                {
                    Code = ResultCode.修改成功,
                    Message = "权限信息更新成功"
                };
            }
            catch (Exception ex)
            {
                // 记录日志
                logger.LogError($"UpdatePermissionCommandHandler.Handle方法异常：{ex.Message},{ex.StackTrace}");
                return new Apiresult<int>
                {
                    Code = ResultCode.修改失败,
                    Message = "系统异常，权限信息更新失败"
                };
            }
        }
    }
}